package com.merugu.school.util;

import com.merugu.school.beans.StudentBean;
import com.merugu.school.beans.UserBean;
import com.merugu.school.hibernate.Student;
import com.merugu.school.hibernate.User;
import com.merugu.school.hibernate.UserRole;
import org.springframework.web.jsf.FacesContextUtils;

import javax.faces.context.FacesContext;

/**
 * Utility class for Spring related operations.
 *
 * @author Raveendra Merugu
 */
public class SpringUtil {

    /**
     * Returns the bean from spring bean factory by given name
     *
     * @param name  name of the bean.
     * @param clazz Return class name
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()).getBean(name, clazz);
    }

    /**
     * Converts User object  to UserBean
     *
     * @param user User
     * @return UserBean
     */

    public static UserBean convert(User user, boolean eager) {

        UserBean userBean = null;
        if (eager) {
            userBean = UserBean.getUserBean();
        } else {
            userBean = new UserBean();
        }

        userBean.setFirstName(user.getFirstName());
        userBean.setLastName(user.getLastName());
        userBean.setUserName(user.getUserName());
        userBean.setUserRole(user.getRole().getRole());

        return userBean;
    }

    /**
     * Converts the UserBean to User
     *
     * @param userBean UserBean
     * @return User
     */
    public static User convert(UserBean userBean) {
        User user = new User();
        user.setFirstName(userBean.getFirstName());
        user.setLastName(userBean.getLastName());
        user.setUserName(userBean.getUserName());
        user.setPassword(userBean.getPassword());
        //Sets the user role
        UserRole userRole = new UserRole();
        userRole.setRole(userBean.getUserRole());
        user.setRole(userRole);
        return user;
    }


    /**
     * Converts and returns from @StudentBean to @Student
     *
     * @param studentBean
     * @return Student
     */
    public static Student convert(StudentBean studentBean) {

        Student ret = new Student();
        ret.setFirstName(studentBean.getFirstName());
        ret.setLastName(studentBean.getLastName());
        ret.setSurName(studentBean.getSurName());
        ret.setFatherName(studentBean.getFatherName());
        ret.setMotherName(studentBean.getMotherName());
        ret.setGender(studentBean.getGender());
        ret.setDateOfBirth(studentBean.getDateOfBirth());
        ret.setDateOfJoin(studentBean.getDateOfJoin());

        return ret;
    }
}
